package com.lzy.chat.d_controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzy.chat.a_entity.Message;
import com.lzy.chat.a_entity.User;
import com.lzy.chat.c_service.MessageService;
import com.lzy.chat.c_service.UserService;
import com.lzy.chat.e_util.JsonResult;
import com.lzy.chat.g_annotation.CurrentUser;
import com.lzy.chat.g_annotation.NeedToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("message")
public class MessageController extends BaseController {
    private MessageService messageService;

    private UserService userService;

    @Autowired
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @NeedToken
    @RequestMapping("getHistoryMessage")
    public JsonResult<List<Message>> getHistoryMessage(@CurrentUser User user, long date, Integer friendId) {
        Date d = new Date(date);
        PageHelper.startPage(1, 6);
        List<Message> historyMessage = messageService.getHistoryMessage(d, user.getId(), friendId);
        PageInfo<Message> pageInfo = new PageInfo<>(historyMessage);
        JsonResult<List<Message>> jsonResult = new JsonResult<>();
        jsonResult.setState(ok);
        jsonResult.setMessage(pageInfo.isHasNextPage() + "");
        jsonResult.setData(historyMessage);
        return jsonResult;
    }

    @NeedToken
    @RequestMapping("getGroupHistoryMessage")
    public JsonResult<List<Message>> getGroupHistoryMessage(long date, Integer gid) {
        Date d = new Date(date);
        PageHelper.startPage(1, 6);
        List<Message> historyMessage = messageService.getGroupHistoryMessage(gid, d);
        PageInfo<Message> pageInfo = new PageInfo<>(historyMessage);
        JsonResult<List<Message>> jsonResult = new JsonResult<>();
        jsonResult.setState(ok);
        jsonResult.setMessage(pageInfo.isHasNextPage() + "");
        for (Message message : historyMessage) {
            User u = userService.getInfoById(message.getFromId());
            message.setUser(u);
        }
        jsonResult.setData(historyMessage);
        return jsonResult;
    }
}
